package com.shd.edanpei.presenter;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.shd.edanpei.R;
import com.shd.edanpei.base.network.exception.ResponeThrowable;
import com.shd.edanpei.base.rxbus.Subscribe;
import com.shd.edanpei.bean.ImgInfoBean;
import com.shd.edanpei.bean.OrderListModel;
import com.shd.edanpei.bean.UrlModel;
import com.shd.edanpei.customer.activity.PayActivity;
import com.shd.edanpei.enums.UrlEnum;
import com.shd.edanpei.ui.activity.CarNeedDataActivity1;
import com.shd.edanpei.ui.activity.CustomerInfoActivity;
import com.shd.edanpei.ui.activity.FileListActivity;
import com.shd.edanpei.ui.activity.FileListPersonalAndEnterpActivity;
import com.shd.edanpei.ui.activity.HouseNeedDataActivity1;
import com.shd.edanpei.ui.activity.PersionalActivity;
import com.shd.edanpei.ui.activity.UpdateLocation;
import com.shd.edanpei.base.BasePresenterImpl;
import com.shd.edanpei.common.Constant;
import com.shd.edanpei.base.data.RxBusCode;
import com.shd.edanpei.base.dialog.DialogUtil;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.model.NoDataResponse;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.base.rxbus.RxBus;
import com.shd.edanpei.bean.OrderDetailsModel;
import com.shd.edanpei.bean.StatusBean;
import com.shd.edanpei.bean.TakeOrderBean;
import com.shd.edanpei.presenter.contract.OrderDetailsContract;
import com.shd.edanpei.order.ItemDialog;
import com.shd.edanpei.order.OrderApiService;
import com.shd.edanpei.enums.OrderTypeEnum;
import com.shd.edanpei.enums.StatusEnum;
import com.shd.edanpei.util.ToastUtil;

import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by mc on 2018/9/25.
 * yang-wen-wen
 */

public class OrderDetailsPresenter extends BasePresenterImpl<OrderDetailsContract.OrderDetailsIView>
        implements OrderDetailsContract.OrderDetailsIPresenter {

    public OrderDetailsPresenter(OrderDetailsContract.OrderDetailsIView mView) {
        super(mView);
        RxBus.get().register(this);
    }

    @Override
    public void requetData(int orderID) {
        mBaseIView.showLoading("");
        ApiCreator.getApi().orderDetails(orderID)
                .compose(RxTransformer.<OrderDetailsModel>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<OrderDetailsModel>() {
                    @Override
                    protected void onSuccess(OrderDetailsModel data) {
                        mBaseIView.setData(data);
                    }

                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });
    }


    @Override
    public void take(final int orderID, final int index) {
        View view = View.inflate(mBaseIView.getContext(), R.layout.dialog_take_code, null);
        final EditText etCode = view.findViewById(R.id.et_code);
        View sure = view.findViewById(R.id.sure);

        final Dialog takeDialog = new Dialog(mBaseIView.getContext(), R.style.inputDialog);
        takeDialog.setContentView(view);
        takeDialog.setCanceledOnTouchOutside(true);
        takeDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                etCode.setText("");
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = etCode.getText().toString();
                if (!TextUtils.isEmpty(code)) {
                    takeDialog.dismiss();
                    takeOrder(orderID, index, code);
                }
            }
        });
        takeDialog.show();
    }

    private void takeOrder(int orderID, final int index, String code) {
        mBaseIView.showLoading("正在抢单...");
        ApiCreator.getApi().takeOrder(orderID, code)
                .compose(RxTransformer.<TakeOrderBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<TakeOrderBean>() {
                    @Override
                    protected void onSuccess(TakeOrderBean data) {
                        if (data.getCode().equals("1")) {
                            ToastUtil.showToast("抢单成功");
                            RxBus.get().send(RxBusCode.TAKE_ORDER_SUCCESS, new StatusBean(index, 0));
                        } else if (data.getCode().equals("3")) {
                            ToastUtil.showToast(data.getMsg());
                            RxBus.get().send(RxBusCode.TAKE_ORDER_FAIL, new StatusBean(index, 0));
                        }

                    }

                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });
    }


    @Override
    public void sureGetLone(Bundle bundle) {
        mBaseIView.showLoading("");
        final int orderID = bundle.getInt(Constant.ORDER_ID);
        final int orderType = bundle.getInt(Constant.ORDER_TYPE);
        final int index = bundle.getInt(Constant.INDEX);
        DialogUtil.infoDialog(mBaseIView.getContext(), "立即确认", "请务必确认您已收到终审金额", null, null, new DialogUtil.SureListener() {
            @Override
            public void sure() {
                ApiCreator.getApi().sureGetLoan(orderID, orderType)
                        .compose(RxTransformer.<NoDataResponse>errorHandle())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<NoDataResponse>() {
                            @Override
                            protected void onSuccess(NoDataResponse data) {
                                RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.success.getStatus()));
                                DialogUtil.hintDialog(mBaseIView.getContext(), R.drawable.ic_success, "确认成功");
                            }

                            @Override
                            public void onFinish() {
                                mBaseIView.stopLoading();
                            }
                        });
            }
        });

    }

    @Override
    public void remove(final int orderID, final int orderType, final int index, final int type) {
        DialogUtil.infoDialog(mBaseIView.getContext(), "温馨提示", "您确定要删除此订单吗？", null, null, new DialogUtil.SureListener() {
            @Override
            public void sure() {
                if (type == Constant.ME_ORDER) {
                    ApiCreator.getApi().userDelete(orderID, orderType)
                            .compose(RxTransformer.<NoDataResponse>errorHandle())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new BaseObserver<NoDataResponse>() {
                                @Override
                                protected void onSuccess(NoDataResponse data) {
                                    RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.deleted.getStatus()));
                                    ToastUtil.showToast("删除成功");
                                    mBaseIView.getContext().finish();
                                }
                            });
                } else if (type == Constant.SHARE_ORDER) {
                    ApiCreator.getApi().deleteOrder(orderID, orderType)
                            .compose(RxTransformer.<NoDataResponse>errorHandle())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new BaseObserver<NoDataResponse>() {
                                @Override
                                protected void onSuccess(NoDataResponse data) {
                                    RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.deleted.getStatus()));
                                    ToastUtil.showToast("删除成功");
                                    mBaseIView.getContext().finish();
                                }
                            });
                }


            }
        });

    }

    private Dialog updateDialog;

    @Override
    public void updataOrder(final Bundle bundle, final int orderID, final int status) {
        final int orderType = bundle.getInt(Constant.ORDER_TYPE);
        bundle.putInt(Constant.FROM, 1);
        if (updateDialog == null) {
            View view = View.inflate(mBaseIView.getContext(), R.layout.dialog_updata_order_select, null);
            view.findViewById(R.id.update_location).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mBaseIView.startActivity(UpdateLocation.class, bundle);
//                    updateDialog.dismiss();
                }
            });
            view.findViewById(R.id.update_info).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bundle.putInt(Constant.FROM, CustomerInfoActivity.UPDATA);
                    mBaseIView.startActivity(CustomerInfoActivity.class, bundle);
//                    updateDialog.dismiss();
                }
            });
            view.findViewById(R.id.update_data).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bundle.putInt(Constant.FROM, 1);
                    if (orderType == OrderTypeEnum.car.getKey()) {
                        mBaseIView.startActivity(CarNeedDataActivity1.class, bundle);
                    } else if (orderType == OrderTypeEnum.house.getKey()) {
                        mBaseIView.startActivity(HouseNeedDataActivity1.class, bundle);
                    }else if (orderType == OrderTypeEnum.personal.getKey()) {
                        mBaseIView.startActivity(PersionalActivity.class, bundle);
                    }else if (orderType == OrderTypeEnum.enterprise.getKey()) {
                        mBaseIView.startActivity(PersionalActivity.class, bundle);
                    }
//                    updateDialog.dismiss();
                }
            });
            view.findViewById(R.id.update_file).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bundle.putInt(Constant.FROM, 1);
                    bundle.putBoolean("isMarry", isMarry);
                    bundle.putBoolean("isCar", isCar);
                    bundle.putBoolean("other", other);
                    bundle.putBoolean("company", company);
                    if(orderType==OrderTypeEnum.car.getKey()||orderType==OrderTypeEnum.house.getKey()){
                        mBaseIView.startActivity(FileListActivity.class, bundle);
                    }else{
                        mBaseIView.startActivity(FileListPersonalAndEnterpActivity.class, bundle);
                    }
                   // mBaseIView.startActivity(FileListActivity.class, bundle);
//                    updateDialog.dismiss();
                }
            });
            view.findViewById(R.id.tv_submit).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sureUpdate(orderID, status, bundle.getInt(Constant.INDEX));

                }
            });
            updateDialog = new Dialog(mBaseIView.getContext(), R.style.dialog);
            updateDialog.setContentView(view);
            updateDialog.setCanceledOnTouchOutside(true);
        }
        updateDialog.show();
    }


    private boolean isMarry = false;

    @Subscribe(code = RxBusCode.isMarry)
    public void setMarry(Boolean b) {
        isMarry = b;
    }


    private boolean isCar = false;
    @Subscribe(code = RxBusCode.isCar)
    public void setCar(Boolean b){
        isCar = b;
    }

    private boolean other = false;

    @Subscribe(code = RxBusCode.other)
    public void setOther(Boolean b){
        other = b;
    }

    private boolean company = false;
    @Subscribe(code = RxBusCode.company)
    public void setCompany(Boolean b){
        company = b;
    }



    @Override
    public void userUndo(final int orderID, final int orderType, final int index, final boolean payDeposit) {
        new ItemDialog(mBaseIView.getContext(), "撤销理由", R.array.user_undo_reason, new ItemDialog.Listener() {
            @Override
            public void setInfo(String str) {
                mBaseIView.showLoading("取消中...");
                OrderApiService.userUndo(str, orderID, orderType, index, payDeposit, new OrderApiService.Listener() {
                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });
            }
        }).show();
    }

    @Override
    public void bankUndo(final int orderID, final int orderType, final int index, final boolean payDeposit) {
        new ItemDialog(mBaseIView.getContext(), "撤销理由", R.array.bank_undo_reson, new ItemDialog.Listener() {
            @Override
            public void setInfo(String str) {
                OrderApiService.bankUndo(str, orderID, orderType, index, new OrderApiService.Listener() {
                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });
            }
        }).show();
    }


    @Override
    public void bankRemove(final int orderID, final int orderType, final int index) {
        DialogUtil.infoDialog(mBaseIView.getContext(), "温馨提示", "您确定要删除此订单吗？", null, null, new DialogUtil.SureListener() {
            @Override
            public void sure() {
                ApiCreator.getApi().deleteOrder(orderID, orderType)
                        .compose(RxTransformer.<NoDataResponse>errorHandle())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<NoDataResponse>() {
                            @Override
                            protected void onSuccess(NoDataResponse data) {
                                RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.deleted.getStatus()));
                                ToastUtil.showToast("删除成功");
                                mBaseIView.getContext().finish();
                            }
                        });

            }
        });
    }
    private boolean isHourse = false;
    @Subscribe(code =RxBusCode.ishourse)
    public  void setIsHourse(Boolean b){
        isHourse=b;
    }
    private boolean isInsurance = false;
    @Subscribe(code =RxBusCode.isinsurance)
    public  void setIsInsurance(Boolean b){
        isInsurance=b;
    }
    private boolean isFun = false;
    @Subscribe(code =RxBusCode.isfun)
    public  void setIsFun(Boolean b){
        isFun=b;
    }
    private void sureUpdate(final int orderID, final int status, final int index) {

        ApiCreator.getApi().getFileData(orderID)
                .compose(RxTransformer.<ImgInfoBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<ImgInfoBean>() {
                    @Override
                    protected void onSuccess(ImgInfoBean data) {
                        ArrayList<String> list = new ArrayList<>();
                        list.add("");

                        if (data.getRoomCert().size() == 0 && isHourse) {
                            ToastUtil.showToast("请上房产证信息");
                            return;
                        }
                        if (data.getCarWarranty().size() == 0 && isInsurance) {
                            ToastUtil.showToast("请上传保单信息");
                            return;
                        }
                        if (status == StatusEnum.cancel.getStatus()
                                || status == StatusEnum.waitRepay.getStatus()
                                || status == StatusEnum.repaySuccess.getStatus()) {
                            ApiCreator.getApi().comfirmUpdate(orderID)
                                    .compose(RxTransformer.<NoDataResponse>errorHandle())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new BaseObserver<NoDataResponse>() {
                                        @Override
                                        protected void onSuccess(NoDataResponse data) {
                                            updateDialog.dismiss();
                                            if (status == StatusEnum.repaySuccess.getStatus()) {
                                                RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.unpaid.getStatus()));
                                            } else {
                                                RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.applying.getStatus()));
                                            }
                                        }
                                    });
                        }
                    }});

    }


    public void againApply(final int orderID, final int orderType, final int index) {
        ApiCreator.getApi().againApply(orderID, orderType)
                .compose(RxTransformer.<NoDataResponse>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<NoDataResponse>() {
                    @Override
                    protected void onSuccess(NoDataResponse data) {
                        RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.unpaid.getStatus()));
                        DialogUtil.hintDialog(mBaseIView.getContext(), R.drawable.ic_success, "申请成功");
                    }
                });
    }


    /**
     * 检查是否授权
     */
    public void checkAuthorization(OrderDetailsModel model, Bundle bundle) {

        if (TextUtils.isEmpty(model.getBaseInfo().getLoanCreditPath())) {
            //未授权
            getH5(model,bundle);
        } else {
            //已授权
            mBaseIView.startActivity(PayActivity.class, bundle);
        }


    }

    public void getH5(final OrderDetailsModel model, final Bundle bundle) {
        ApiCreator.getApi().getUrl(UrlEnum.f.getType())
                .compose(RxTransformer.<UrlModel>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<UrlModel>() {
                    @Override
                    protected void onSuccess(UrlModel data) {
                        showDialog(data.getUrlShow(), model,bundle);

                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        super.onFailure(throwable);

                    }
                });
    }

    private void showDialog(String url, final OrderDetailsModel model, final Bundle bundle) {
        View view = LayoutInflater.from(mBaseIView.getContext()).inflate(R.layout.dialog_authorized, null);
        WebView webView = view.findViewById(R.id.webview);
        final ProgressBar progressBar = view.findViewById(R.id.progressBar);
        TextView tvDone = view.findViewById(R.id.done);
        final Dialog dialog = new Dialog(mBaseIView.getContext(), R.style.dialog);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        webView.loadUrl(url);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView webView, int i) {
                if (i == 100) {
                    progressBar.setVisibility(View.GONE);
                }
                super.onProgressChanged(webView, i);
            }

        });
        tvDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmAuthoriz(model,bundle);
                dialog.dismiss();
            }

        });

        dialog.show();
    }

    private void confirmAuthoriz(final OrderDetailsModel model, final Bundle bundle) {
        ApiCreator.getApi().confirmAuthoriz(model.getBaseInfo().getOrderId())
                .compose(RxTransformer.<NoDataResponse>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<NoDataResponse>() {
                    @Override
                    protected void onSuccess(NoDataResponse data) {
                        DialogUtil.hintDialog(mBaseIView.getContext(), R.drawable.ic_success2, "授权成功");
                        model.getBaseInfo().setLoanCreditPath("123");
                        mBaseIView.startActivity(PayActivity.class, bundle);
                    }
                });
    }
}
